﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleActor.Test
{
    internal class SchedulingTestServiceScope
    {
        public static SchedulingTestServiceScope Create(Action<ISchedulingTestService> action)
        {
            var ret = new SchedulingTestServiceScope(action);
            return ret;
        }

        public static SchedulingTestServiceScope CreateDetail(
            Action<SchedulingTestServiceProxy, MessageScheduler<ISchedulingTestServant>, SchedulingTestServant> action)
        {
            var ret = new SchedulingTestServiceScope(action);
            return ret;
        }

        private SchedulingTestServant servant;
        private MessageScheduler<ISchedulingTestServant> scheduler;
        private SchedulingTestServiceProxy proxy;
        private Action run;

        private SchedulingTestServiceScope(Action<ISchedulingTestService> action)
        {
            this.run = () => action(this.proxy);

            Run();
        }

        private SchedulingTestServiceScope(
            Action<SchedulingTestServiceProxy, MessageScheduler<ISchedulingTestServant>, SchedulingTestServant> action)
        {
            this.run = () => action(this.proxy, this.scheduler, this.servant);

            Run();
        }

        private void Run()
        {
            servant = new SchedulingTestServant();
            scheduler = new MessageScheduler<ISchedulingTestServant>("Service", servant);
            proxy = new SchedulingTestServiceProxy(scheduler);

            proxy.Start().Wait();

            run();

            proxy.Stop().Wait();
        }
    }
}
